package com.ciwong.epaper.modules.me.ui;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.TimeoutError;
import com.ciwong.epaper.R;
import com.ciwong.epaper.modules.bookstore.adapter.MembersAdapter;
import com.ciwong.epaper.modules.bookstore.bean.StudentGroupBean;
import com.ciwong.epaper.modules.clazz.bean.StudentBean;
import com.ciwong.epaper.modules.epaper.dao.EpaperDao;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.libs.utils.NetworkUtils;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.utils.ToastUtil;
import com.ciwong.mobilelib.widget.CWDialog;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 分组页面
 */
public class MembersActivity extends BaseActivity {

    private ExpandableListView expandableListView;


    private MembersAdapter membersAdapter;
    //学生集合
    private List<StudentBean> studentBeans;

    private TextView choose_stu_class_title;
    private EditText team_name_edit;
    private RelativeLayout choose_stu_finish_lay;
    private TextView choose_stu_finish_text;
    //组名
    private String teamname;
    //班级id
    private int classId;
    private String clientId;
    //是否分组
    private Boolean isGrouping;
    //组id
    private int teamId;
    private TextView del_class_team;
    private CWDialog cwDialog;
    //删除分组组名
    private String delTeamName;

    private ImageView stu_class_go_back;
    //小组集合
    private List<StudentGroupBean> studentGroupBeanList;
    //是否修改成功
    private Boolean isUpeSuccess = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }


    @Override
    protected int setView() {
        return R.layout.activity_stu_class;
    }

    @Override
    protected void findViews() {
        expandableListView = findViewById(R.id.stu_members_list);
        stu_class_go_back = findViewById(R.id.stu_class_go_back);
        choose_stu_class_title = findViewById(R.id.choose_stu_class_title);
        team_name_edit = findViewById(R.id.team_name_edit);
        choose_stu_finish_text = findViewById(R.id.choose_stu_finish_text);
        choose_stu_finish_lay = findViewById(R.id.choose_stu_finish_lay);
        del_class_team = findViewById(R.id.del_team);
        stu_class_go_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        expandableListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
                return true;
            }
        });
    }

    @Override
    protected void init() {
        hideTitleBar();
        Intent intent = getIntent();
        classId = intent.getIntExtra(IntentFlag.INTENT_FLAG_CLASS_ID, 0);
        clientId = intent.getStringExtra(IntentFlag.INTENT_FLAG_CLIENT_ID);
        teamId = intent.getIntExtra(IntentFlag.INTENT_FLAG_TEAM_ID, 0);
        delTeamName = intent.getStringExtra(IntentFlag.INTENT_FLAG_TEAM_NAME);
        isGrouping = intent.getBooleanExtra(IntentFlag.INTENT_FLAG_BOOLEAN, false);
        if (isGrouping) {
            choose_stu_class_title.setText(getString(R.string.upe_group));
            team_name_edit.setText(delTeamName);
            del_class_team.setVisibility(View.VISIBLE);
        } else {
            choose_stu_class_title.setText(getString(R.string.add_group));
            del_class_team.setVisibility(View.GONE);
        }
    }

    @Override
    protected void initEvent() {
        choose_stu_finish_lay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                addTeam();
            }
        });
        del_class_team.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showDialog();
            }
        });
    }

    /**
     * 删除分组提示框
     */
    public void showDialog() {
        if (null != cwDialog && cwDialog.isShowing()) {
            cwDialog.dismiss();
        }
        cwDialog = new CWDialog(MembersActivity.this);
        cwDialog.setTitle(R.string.str_hint);
        cwDialog.setMessagWidePadding("确定删除" + delTeamName + "分组吗?").setPositiveButton(R.string.str_confirm, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                delTeam();
            }
        }).setNegativeButton(R.string.str_cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                cwDialog.dismiss();
            }
        }).show();

        cwDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                cwDialog.dismiss();
            }
        });
    }

    /**
     * 删除分组
     */
    public void delTeam() {
        EpaperDao.getInstance().delTeam(teamId, new BaseCallBack() {
            @Override
            public void failed(int errorCode, Object data) {
                ToastUtil.INSTANCE.toastCenterError(getString(R.string.del_faild_try_later));
            }

            @Override
            public void failed(Object data) {
                ToastUtil.INSTANCE.toastCenterError(getString(R.string.del_faild_try_later));
            }

            @Override
            public void success(Object data) {
                ToastUtil.INSTANCE.toastCenterSuccess(getString(R.string.del_success));
                isUpeSuccess = true;
                finish();
            }
        });
    }

    /**
     * 设置选中学生人数
     */
    public void setChooseStuCount() {
        int checkCountAll = 0;
        for (int i = 0; i < studentGroupBeanList.size(); i++) {
            int checkCount = studentGroupBeanList.get(i).getCheckCount();
            checkCountAll = checkCountAll + checkCount;
        }
        choose_stu_finish_text.setText("完成（已选" + checkCountAll + "个学生）");
    }

    /**
     * 创建班级小组
     */
    public void addTeam() {
        StringBuffer str = new StringBuffer();
        for (int i = 0; i < studentGroupBeanList.size(); i++) {
            List<StudentBean> list = studentGroupBeanList.get(i).getList();
            for (int i1 = 0; i1 < list.size(); i1++) {

                if (list.get(i1).getCheckStatus() == 1) {
                    if (null == str || "".equals(str) || str.length() == 0) {
                        str.append(list.get(i1).getUserId());
                    } else {
                        str.append("," + list.get(i1).getUserId());
                    }

                }
            }
        }
        teamname = team_name_edit.getText().toString();
        if ("".equals(teamname)) {
            ToastUtil.INSTANCE.toastCenterError(getString(R.string.please_edit_group_name));
            return;
        }
        if (str.length() == 0) {
            ToastUtil.INSTANCE.toastCenterError(getString(R.string.please_choose_stu));
            return;
        }
        if (isGrouping) {
            EpaperDao.getInstance().editTeam(teamname, classId, str.toString(), teamId, new BaseCallBack() {
                @Override
                public void failed(int errorCode, Object data) {
                    ToastUtil.INSTANCE.toastCenterError(getString(R.string.upe_member_faild_try_later));
                }

                @Override
                public void failed(Object data) {
                    if (data instanceof TimeoutError) {
                        hideCricleProgress();
                        ToastUtil.INSTANCE.toastCenterError(getString(R.string.load_faild_check_net_work));
                    } else {
                        hideCricleProgress();
                        ToastUtil.INSTANCE.toastCenterError(getString(R.string.upe_member_faild_try_later));
                    }
                }

                @Override
                public void success(Object data) {
                    super.success(data);
                    ToastUtil.INSTANCE.toastCenterSuccess(getString(R.string.upe_member_success));
                    isUpeSuccess = true;
                    finish();
                }
            });

        } else {

            EpaperDao.getInstance().addTeam(teamname, classId, str.toString(), new BaseCallBack() {
                @Override
                public void failed(int errorCode, Object data) {
                    ToastUtil.INSTANCE.toastCenterError(getString(R.string.add_member_faild_try_later));
                }

                @Override
                public void failed(Object data) {
                    if (data instanceof TimeoutError) {
                        hideCricleProgress();
                        ToastUtil.INSTANCE.toastCenterError(getString(R.string.load_faild_check_net_work));
                    } else {
                        hideCricleProgress();
                        ToastUtil.INSTANCE.toastCenterError(getString(R.string.add_member_faild_try_later));
                    }
                }

                @Override
                public void success(Object data) {
                    super.success(data);
                    ToastUtil.INSTANCE.toastCenterSuccess(getString(R.string.add_member_success));
                    isUpeSuccess = true;
                    finish();
                }
            });

        }
    }


    @Override
    protected void loadData() {
        showCricleProgress();
        getMembers(classId, clientId, 1, 1, 1);

    }

    /**
     * 获取班级成员
     * @param classId 班级id
     * @param clientId
     * @param getIntegral
     * @param getVip
     * @param role
     */
    public void getMembers(int classId, String clientId, int getIntegral, int getVip, int role) {

        EpaperDao.getInstance().getmembers(classId, clientId, getIntegral, getVip, role, new BaseCallBack() {
            @Override
            public void failed(int errorCode, Object data) {
                hideCricleProgress();
                if (!NetworkUtils.isOnline()) {
                    ToastUtil.INSTANCE.toastCenterError(getString(R.string.load_faild_check_net_work));
                    return;
                }
            }

            @Override
            public void failed(Object data) {
                if (data instanceof TimeoutError) {
                    hideCricleProgress();
                    ToastUtil.INSTANCE.toastCenterError(getString(R.string.load_faild_check_net_work));
                } else {
                    hideCricleProgress();
                    ToastUtil.INSTANCE.toastCenterError(getString(R.string.load_faild_try_later));
                }
            }

            @Override
            public void success(Object data) {

                hideCricleProgress();
                if (null != data && data instanceof ArrayList) {
                    studentBeans = (List<StudentBean>) data;

                    studentGroupBeanList = new ArrayList<>();
                    //遍历数据 将同一小组学生存放至同一集合当中
                    Map<Integer, String> map = new HashMap<>();
                    for (StudentBean stu : studentBeans) {
                        map.put(stu.getTeamId(), stu.getTeamName());
                    }
                    Set<Integer> integers = map.keySet();
                    for (Integer integer : integers) {
                        StudentGroupBean studentGroupBean = new StudentGroupBean();
                        List<StudentBean> stuList = new ArrayList<>();
                        for (int i = 0; i < studentBeans.size(); i++) {
                            if (studentBeans.get(i).getTeamId() == integer) {
                                stuList.add(studentBeans.get(i));
                            }
                        }
                        if (teamId == integer && teamId != 0) {
                            for (int i = 0; i < stuList.size(); i++) {
                                stuList.get(i).setCheckStatus(1);
                            }
                            studentGroupBean.setList(stuList);
                            studentGroupBean.setCheckCount(stuList.size());
                            studentGroupBean.setTeamId(integer);
                        } else {
                            studentGroupBean.setList(stuList);
                            studentGroupBean.setCheckCount(0);
                            studentGroupBean.setTeamId(integer);
                        }
                        studentGroupBeanList.add(studentGroupBean);
                    }
                    membersAdapter = new MembersAdapter(MembersActivity.this, studentGroupBeanList);
                    expandableListView.setAdapter(membersAdapter);
                    for (int i = 0; i < studentGroupBeanList.size(); i++) {
                        expandableListView.expandGroup(i);
                    }

                }

            }
        });

    }

    @Override
    public void finish() {
        if (isUpeSuccess) {
            setResult();
        }
        super.finish();
    }

    //修改成功
    public void setResult() {
        setResult(RESULT_OK);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

}
